package capaDatos;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import utiles.UIDGenerator;

import capaLogica.Evento;
import capaLogica.PerfilGrupo;

public class EventoDAO {


	/**
	 * Atributo que crea la conexion a la bd
	 */
	private Connection conn;
	
	/**
	 * Constructor de la clase
	 */
	public EventoDAO(){
		conn = (Connection) ConnectionManager.getInstance().checkOut();
	}
	
	@Override
	 protected void finalize() {
       ConnectionManager.getInstance().checkIn(conn);
	}
	
	public Evento recuperarEventoById(String evento) {
        PreparedStatement stmt = null;
        ResultSet result = null;
        Evento p = null;
        String sql = "SELECT * FROM evento WHERE (idEvento = ?) ";

        try {
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, evento);
            result = stmt.executeQuery();

            if ( result.next() ){
	            p = new Evento();
	            p.setIdEvento(result.getString("idEvento"));
	            p.setDescripcion(result.getString("descripcion"));
	            p.setDireccion(result.getString("direccion"));
	            p.setFechaEvento(result.getDate("fechaEvento"));
	            p.setIdUsuarioCreador(result.getString("idUsuarioCreador"));
	            p.setVotos(result.getInt("votos"));
	            p.setHora(result.getString("hora"));
            }
            
        } catch (SQLException e) {
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
            try {
                if (result != null) {
                    result.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
            }
        }
        return p;
    }
	
	public List<Evento> recuperarEventoByIdUsuario(String idUsuario) {
        PreparedStatement stmt = null;
        ResultSet result = null;
        List<Evento> listaEventos = new ArrayList<Evento>();
        String sql = "SELECT * FROM eventoUsuariosAsociados WHERE (idUsuario = ?) ";

        try {
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, idUsuario);
            result = stmt.executeQuery();

            while( result.next() ){
	            Evento p = new Evento();
	          String idEvento = result.getString("idEvento");
	          p = recuperarEventoById(idEvento);
	          listaEventos.add(p);
            }
            
        } catch (SQLException e) {
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
            try {
                if (result != null) {
                    result.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
            }
        }
        return listaEventos;
    }
	
	public Evento insertarEvento(Evento user) {
		String sql = "INSERT INTO evento (idEvento,idUsuarioCreador,fechaEvento,hora,idCiudad,direccion,descripcion,votos) VALUES (?,?,?,?,?,?,?,?) ";
		PreparedStatement stmt = null;
		
		try {
			stmt = conn.prepareStatement(sql);
			user.setIdEvento(UIDGenerator.getInstance().getKey());
			
			stmt.setString(1, user.getIdEvento());
			stmt.setString(2, user.getIdUsuarioCreador());
			
			java.util.Date fechaNoticia= user.getFechaEvento();
			
			stmt.setDate(3,  new java.sql.Date(fechaNoticia.getTime()));
			
			stmt.setString(4, user.getHora());
			stmt.setString(5, user.getIdCiudad());
			stmt.setString(6, user.getDireccion());
			stmt.setString(7, user.getDescripcion());
			stmt.setInt(8, user.getVotos());
			stmt.executeUpdate();

			insertarTablaAsociativa(user.getIdEvento(),user.getIdUsuarioCreador());
			
		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
					
				}
			} catch (SQLException e) {
			}
		}
		
		return user;
	}
	
	public void insertarTablaAsociativa(String idEvento, String idUsuario){
		String sql = "INSERT INTO eventoUsuariosAsociados (idEventoUsuarios,idEvento,idUsuario) VALUES (?,?,?) ";
		PreparedStatement stmt = null;
		
		try {
			stmt = conn.prepareStatement(sql);
			
			stmt.setString(1, UIDGenerator.getInstance().getKey());
			stmt.setString(2, idEvento);
			stmt.setString(3, idUsuario);
			stmt.executeUpdate();
		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
					
				}
			} catch (SQLException e) {
			}
		}
	}
	
	public List<Evento> recuperarEventosBusqueda(Evento evento) {
        PreparedStatement stmt = null;
        ResultSet result = null;
        List<Evento> lista = new ArrayList<Evento>();
        String sql = "SELECT * FROM evento WHERE (idCiudad = ?)";
        if ( evento.getFechaEvento() != null ){
        	sql = "SELECT * FROM evento WHERE (idCiudad = ?) AND (fechaEvento = ?) ";
        }
        try {
        	 if ( evento.getFechaEvento() != null ){
        		 
        		 java.util.Date fechaNoticia= evento.getFechaEvento();
        		 java.sql.Date fecha2 = new java.sql.Date(fechaNoticia.getTime());

        		 stmt = conn.prepareStatement(sql);
                 stmt.setString(1, evento.getIdCiudad());
                 stmt.setDate(2,  fecha2);
                 result = stmt.executeQuery();
             }else{
	            stmt = conn.prepareStatement(sql);
	            stmt.setString(1, evento.getIdCiudad());
	            result = stmt.executeQuery();
             }

            while( result.next() ){
	            Evento p = new Evento();
	            p.setIdEvento(result.getString("idEvento"));
	            p.setDescripcion(result.getString("descripcion"));
	            p.setDireccion(result.getString("direccion"));
	            p.setFechaEvento(result.getDate("fechaEvento"));
	            p.setIdUsuarioCreador(result.getString("idUsuarioCreador"));
	            p.setVotos(result.getInt("votos"));
	            p.setHora(result.getString("hora"));
	            lista.add(p);
            }
            
        } catch (SQLException e) {
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
            try {
                if (result != null) {
                    result.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
            }
        }
        return lista;
    }
	
	public void actualizarEvento(Evento p) {
		String sql = "UPDATE evento SET idEvento = ?, idUsuarioCreador = ?, fechaEvento = ?, hora = ?, idCiudad = ?, direccion = ?, descripcion = ?, votos = ?  WHERE (idEvento = ?)";
		PreparedStatement stm = null;
		try {
			
			stm = conn.prepareStatement(sql);
			stm.setString(1, p.getIdEvento());
			stm.setString(2, p.getIdUsuarioCreador());
			stm.setDate(3, new java.sql.Date(p.getFechaEvento().getTime()));
			stm.setString(4, p.getHora());
			stm.setString(5, p.getIdCiudad());
			stm.setString(6, p.getDireccion());
			stm.setString(7, p.getDescripcion());
			stm.setInt(8, p.getVotos());
			stm.setString(9, p.getIdEvento());
			stm.executeUpdate();

		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (stm != null) {
					stm.close();
				}
			} catch (SQLException e) {

			}
		}
	}

}
